const gameArea = document.getElementById('gameArea');
const gameSize = { width: 400, height: 400 };
const cellSize = 20;
const gameSpeed = 80; // 调整游戏速度
let snake = [{x: 160, y: 200}, {x: 140, y: 200}, {x: 120, y: 200}];
let apple = {x: 300, y: 200};
let dx = cellSize; // 初始水平速度
let dy = 0; // 初始垂直速度
let changingDirection = false;
let gameInterval;

function createDiv(className, x, y) {
    const div = document.createElement('div');
    div.className = className;
    div.style.left = `${x}px`;
    div.style.top = `${y}px`;
    return div;
}

function updateGameArea() {
    // 清除gameArea
    gameArea.innerHTML = '';
    // 绘制蛇
    snake.forEach(part => {
        const snakePart = createDiv('snake', part.x, part.y);
        gameArea.appendChild(snakePart);
    });
    // 绘制苹果
    const appleElement = createDiv('apple', apple.x, apple.y);
    gameArea.appendChild(appleElement);
}

function moveSnake() {
    const head = { x: snake[0].x + dx, y: snake[0].y + dy };
    snake.unshift(head);
    const hasEatenApple = snake[0].x === apple.x && snake[0].y === apple.y;
    if (hasEatenApple) {
        placeApple();
    } else {
        snake.pop();
    }
}

function changeDirection(event) {
    if (changingDirection) return;
    changingDirection = true;
    const keyPressed = event.keyCode;
    const goingUp = dy === -cellSize;
    const goingDown = dy === cellSize;
    const goingRight = dx === cellSize;
    const goingLeft = dx === -cellSize;
    if (keyPressed === 37 && !goingRight) { dx = -cellSize; dy = 0; }
    if (keyPressed === 38 && !goingDown) { dx = 0; dy = -cellSize; }
    if (keyPressed === 39 && !goingLeft) { dx = cellSize; dy = 0; }
    if (keyPressed === 40 && !goingUp) { dx = 0; dy = cellSize; }
}

function randomTen(min, max) {
    return Math.round((Math.random() * (max-min) + min) / cellSize) * cellSize;
}

function placeApple() {
    apple = {
        x: randomTen(0, gameSize.width - cellSize),
        y: randomTen(0, gameSize.height - cellSize)
    };
}

function main() {
    if (didGameEnd()) return;
    changingDirection = false;
    setTimeout(() => {
        clearCanvas();
        moveSnake();
        updateGameArea();
        main();
    }, gameSpeed);
}

function clearCanvas() {
    gameArea.innerHTML = '';
}

function didGameEnd() {
    for (let i = 4; i < snake.length; i++) {
        if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) return true;
    }
    const hitLeftWall = snake[0].x < 0;
    const hitRightWall = snake[0].x > gameSize.width - cellSize;
    const hitTopWall = snake[0].y < 0;
    const hitBottomWall = snake[0].y > gameSize.height - cellSize;
    return hitLeftWall || hitRightWall || hitTopWall || hitBottomWall;
}

document.addEventListener('keydown', changeDirection);
main(); // 开始游戏